package com.xls.commonlibrary.ad.adn.gm;

import static com.xls.commonlibrary.wxapi.ConstWx.KEY_WX_UNION_ID;

import android.content.SyncContext;
import android.os.Bundle;
import android.util.Log;
import android.webkit.ValueCallback;

import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.DefaultLifecycleObserver;
import androidx.lifecycle.LifecycleOwner;

import com.bytedance.sdk.openadsdk.AdSlot;
import com.bytedance.sdk.openadsdk.TTAdConstant;
import com.bytedance.sdk.openadsdk.TTAdNative;
import com.bytedance.sdk.openadsdk.TTAdSdk;
import com.bytedance.sdk.openadsdk.TTRewardVideoAd;
import com.bytedance.sdk.openadsdk.mediation.MediationConstant;
import com.bytedance.sdk.openadsdk.mediation.ad.MediationAdSlot;
import com.google.gson.Gson;
import com.hjq.toast.Toaster;
import com.orhanobut.logger.Logger;
import com.xls.commonlibrary.ad.adn.reward.bean.AdBean;
import com.xls.commonlibrary.constant.Const;
import com.xls.commonlibrary.util.AESUtil;
import com.xls.commonlibrary.util.AdvertisingBackdropsPointsUtil;
import com.xls.commonlibrary.util.MD5Util;
import com.xls.commonlibrary.util.MMKVUtil;
import com.xls.commonlibrary.util.SysDataUtil;
import com.xls.commonlibrary.util.dislogx.DialogXUtil;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

import cn.hutool.core.lang.copier.SrcToDestCopier;
import io.reactivex.rxjava3.annotations.NonNull;

public class GMRewardUtil {

    //    String mMediaId = "945700410"; // 融合广告位  demo id
    private String mMediaId = ""; // 融合广告位  正式 id


    private static volatile GMRewardUtil singleton = null;
    private String TAG = "GMUtil";

    public boolean isRewardValidM;
    public Bundle extraInfoM;

    private GMRewardUtil() {
    }

    public static GMRewardUtil getInstance() {
        if (singleton == null) {
            synchronized (GMRewardUtil.class) {
                if (singleton == null) {
                    singleton = new GMRewardUtil();
                }
            }
        }
        return singleton;
    }

    ///////////////////////////////////////////////////

    public String mUserId = "157744";


    private TTRewardVideoAd mTTRewardVideoAd; // 插全屏广告对象
    private TTAdNative.RewardVideoAdListener mRewardVideoListener; // 广告加载监听器
    private TTRewardVideoAd.RewardAdInteractionListener mRewardVideoAdInteractionListener; // 广告展示监听器


    AppCompatActivity activity;
    ValueCallback<AdBean> valueCallback;


    /**
     * @param adid          广告位id
     * @param activity
     * @param valueCallback
     */
    public void loadReward(
            @NonNull String adid,
            @NonNull AppCompatActivity activity,
            @NonNull ValueCallback<AdBean> valueCallback
    ) {

        this.mMediaId = adid;
        loadReward(activity, valueCallback);

    }

    public void loadReward(@NonNull AppCompatActivity activity,
                           @NonNull ValueCallback<AdBean> valueCallback
    ) {

        this.activity = activity;
        this.valueCallback = valueCallback;

        addLifecycle();
        initListeners();


        loadRewardVideoAd();

    }

//    private void callbackSuccess(String ecpm, boolean isRewardValid, String transId) {
////        Toaster.show("ecpm:" + ecpm);
//        if (this.valueCallback == null) return;
//
//        // build AdBean for callback
//        AdBean bean = new AdBean();
//        bean.setShowSuccess(true);
//        bean.setEcpm(ecpm);
//        bean.setRewardValid(isRewardValid);
//        bean.setReward(transId);
//        bean.setAdn(Const.TYPE_GROMORE_CSJ);
//        bean.setAdType("激励视频");
//        this.valueCallback.onReceiveValue(bean);
//    }


    private void callbackSuccess(AdBean bean) {
        if (this.valueCallback == null) return;
        this.valueCallback.onReceiveValue(bean);
    }

    private void callbackFail() {

        DialogXUtil.closeLoading();

        if (this.valueCallback == null) return;
        // build AdBean for callback
        AdBean bean = new AdBean();
        bean.setShowSuccess(false);
        this.valueCallback.onReceiveValue(bean);
    }


    private void addLifecycle() {// 重要
        if (this.activity == null) return;

        this.activity.getLifecycle().addObserver(new DefaultLifecycleObserver() {
            // 还有很多生命周期都可以感知
            // 这里只关注 onDestroy()的注销ad对象
            @Override
            public void onDestroy(LifecycleOwner owner) {
                DefaultLifecycleObserver.super.onDestroy(owner);
//                Logger.d("===========LifecycleOwner=========onDestroy===========");


                /** 6、在onDestroy中销毁广告 */
                if (mTTRewardVideoAd != null && mTTRewardVideoAd.getMediationManager() != null) {
                    mTTRewardVideoAd.getMediationManager().destroy();
                }

            }
        });

    }


    private void loadRewardVideoAd() {

        String unionId = MMKVUtil.getInstance().getKV().decodeString(KEY_WX_UNION_ID);
        String packageName = SysDataUtil.getInstance().getPkName();
        Long time= System.currentTimeMillis();
        Gson gson=new Gson();
        Map<String, String> json = new HashMap<>();
        json.put("unionId", unionId);
        json.put("packageName", packageName);
        json.put("time", time+"");
        String sign = MD5Util.encodeByMD5(gson.toJson(json));
        json.put("sign", sign);
        json.put("random", AESUtil.getGUID());
        String Extra= AESUtil.encryptCBC(gson.toJson(json),AESUtil.KEY);
        /** 1、创建AdSlot对象 */
        AdSlot adslot = new AdSlot.Builder()
                .setCodeId(mMediaId)
                .setUserID(unionId)
                .setOrientation(TTAdConstant.ORIENTATION_VERTICAL)
                .setMediationAdSlot(new MediationAdSlot
                        .Builder()
                        .setExtraObject(MediationConstant.ADN_GDT,Extra)//服务端奖励验证透传参数
                        .setExtraObject(MediationConstant.ADN_PANGLE,Extra)//服务端奖励验证透传参数
                        .setExtraObject(MediationConstant.ADN_KS,Extra)//服务端奖励验证透传参数
                        .setExtraObject(MediationConstant.CUSTOM_DATA_KEY_GROMORE_EXTRA,Extra)//服务端奖励验证透传参数
                        .build())
                .build();

        /** 2、创建TTAdNative对象 */
        TTAdNative adNativeLoader = TTAdSdk.getAdManager().createAdNative(this.activity);

        /** 3、创建加载、展示监听器 */
        initListeners();

        /** 4、加载广告 */
        adNativeLoader.loadRewardVideoAd(adslot, mRewardVideoListener);
    }

    // 广告加载成功后，开始展示广告
    private void showRewardVideoAd() {
        if (mTTRewardVideoAd == null) {
            Log.i(TAG, "请先加载广告或等待广告加载完毕后再调用show方法");
            return;
        }
        /** 5、设置展示监听器，展示广告 */
        mTTRewardVideoAd.setRewardAdInteractionListener(mRewardVideoAdInteractionListener);
        mTTRewardVideoAd.showRewardVideoAd(this.activity);
    }

    private void initListeners() {
        // 广告加载监听器
        this.mRewardVideoListener = new TTAdNative.RewardVideoAdListener() {
            @Override
            public void onError(int i, String s) {
                AdvertisingBackdropsPointsUtil.getInstance().JiLiVideo(activity,mMediaId,"",AdvertisingBackdropsPointsUtil.JILIOnClickListener.RewardVideoAd_onError,AdvertisingBackdropsPointsUtil.JILIOnClickListenerSTR.RewardVideoAd_onError+i+s);
                Logger.d("=====RewardVideoAdListener========onError"+"code==="+i+"=====msg"+s+"======id"+mMediaId);
//                Log.i(TAG, "reward load fail: errCode: " + i + ", errMsg: " + s);
//广告拉取不到

                // 黑鸡状态
                //  reward load fail: errCode: 20005, errMsg: 全部代码位请求失败

                callbackFail();

            }

            @Override
            public void onRewardVideoAdLoad(TTRewardVideoAd ttRewardVideoAd) {
                Logger.d("=====RewardVideoAdListener========onRewardVideoAdLoad");
                AdvertisingBackdropsPointsUtil.getInstance().JiLiVideo(activity,mMediaId,"",AdvertisingBackdropsPointsUtil.JILIOnClickListener.RewardVideoAd_onRewardVideoAdLoad,AdvertisingBackdropsPointsUtil.JILIOnClickListenerSTR.RewardVideoAd_onRewardVideoAdLoad);
//                拉到广告
//                Log.i(TAG, "reward load success");
                mTTRewardVideoAd = ttRewardVideoAd;
            }

            @Override
            public void onRewardVideoCached() {
                Logger.d("=====RewardVideoAdListener========onRewardVideoCached");
//                Log.i(TAG, "reward cached success");
            }

            @Override
            public void onRewardVideoCached(TTRewardVideoAd ttRewardVideoAd) {
                Logger.d("=====RewardVideoAdListener========onRewardVideoCached有参数");
                AdvertisingBackdropsPointsUtil.getInstance().JiLiVideo(activity,mMediaId,"",AdvertisingBackdropsPointsUtil.JILIOnClickListener.RewardVideoAd_onRewardVideoCached,AdvertisingBackdropsPointsUtil.JILIOnClickListenerSTR.RewardVideoAd_onRewardVideoCached);

//                Log.i(TAG, "reward cached success 2");
                mTTRewardVideoAd = ttRewardVideoAd;


                showRewardVideoAd();
            }
        };
        // 广告展示监听器
        this.mRewardVideoAdInteractionListener = new TTRewardVideoAd.RewardAdInteractionListener() {
            @Override
            public void onAdShow() {
                AdvertisingBackdropsPointsUtil.getInstance().JiLiVideo(activity,mMediaId,"",AdvertisingBackdropsPointsUtil.JILIOnClickListener.RewardAdInteraction_onAdShow,AdvertisingBackdropsPointsUtil.JILIOnClickListenerSTR.RewardAdInteraction_onAdShow);
//                广告展示
                Logger.d("=====RewardAdInteractionListener========onAdShow");
            }

            @Override
            public void onAdVideoBarClick() {
//                点击广告中的下载按钮
//
                AdvertisingBackdropsPointsUtil.getInstance().JiLiVideo(activity,mMediaId,"",AdvertisingBackdropsPointsUtil.JILIOnClickListener.RewardAdInteraction_onAdVideoBarClick,AdvertisingBackdropsPointsUtil.JILIOnClickListenerSTR.RewardAdInteraction_onAdVideoBarClick);
                Logger.d("=====RewardAdInteractionListener========onAdVideoBarClick");
            }

            @Override
            public void onAdClose() {
                Logger.d("=====RewardAdInteractionListener========onAdClose");
                // get ecpm 重要
//                AdUtils.logEcpmInfo(mTTRewardVideoAd.getMediationManager().getShowEcpm());
                String trans_id="";
                if (extraInfoM!=null){
                    trans_id=extraInfoM.getString("transId");
                }
                AdvertisingBackdropsPointsUtil.getInstance().JiLiVideo(activity,mMediaId,trans_id,AdvertisingBackdropsPointsUtil.JILIOnClickListener.RewardAdInteraction_onAdClose,AdvertisingBackdropsPointsUtil.JILIOnClickListenerSTR.RewardAdInteraction_onAdClose);

                if (null == extraInfoM){
                    callbackFail();
                    return;
                }


                //  callback ecpm
//                callbackSuccess(mTTRewardVideoAd.getMediationManager().getShowEcpm().getEcpm());

//                Logger.d("=====广告展示监听器====reward onAdClose:isRewardValidM====="+isRewardValidM);
//                Logger.d("=====广告展示监听器====reward onAdClose:extraInfoM===="+extraInfoM.toString());


                if (!isRewardValidM) {
//                    Toaster.show("广告数据异常");
                }

                String requestId = mTTRewardVideoAd.getMediationManager().getShowEcpm().getRequestId();
//                Logger.d("=====广告展示监听器====reward onAdClose requestId:===="+extraInfoM.toString());
//                Toaster.show("requestId:"+requestId);

                JSONObject json = new JSONObject();
                for (String key : extraInfoM.keySet()) {
                    try {
                        json.put(key, extraInfoM.get(key));
                    } catch (JSONException e) {
                        throw new RuntimeException(e);
                    }
                }
//                String transId = extraInfo.getString("transId");
//                Logger.d("=====广告展示监听器====reward onAdClose transId:===="+json);

                // set bean
                AdBean bean = new AdBean();
                bean.setShowSuccess(true);
                bean.setEcpm(mTTRewardVideoAd.getMediationManager().getShowEcpm().getEcpm());
                bean.setRequestId(requestId);
                bean.setRewardValid(isRewardValidM);
                bean.setReward(json.toString());// transId在此json中传给后台
                bean.setAdn(Const.TYPE_GROMORE_CSJ);
                bean.setAdType("激励视频");
                bean.setTransId(extraInfoM.getString("transId"));//


                callbackSuccess(bean);


            }

            @Override
            public void onVideoComplete() {
//                播放完成
                Logger.d("=====RewardAdInteractionListener====onVideoComplete====");
                AdvertisingBackdropsPointsUtil.getInstance().JiLiVideo(activity,mMediaId,"",AdvertisingBackdropsPointsUtil.JILIOnClickListener.RewardAdInteraction_onVideoComplete,AdvertisingBackdropsPointsUtil.JILIOnClickListenerSTR.RewardAdInteraction_onVideoComplete);

            }

            @Override
            public void onVideoError() {
                Logger.d("=====RewardAdInteractionListener====onVideoError====");
                callbackFail();
                AdvertisingBackdropsPointsUtil.getInstance().JiLiVideo(activity,mMediaId,"",AdvertisingBackdropsPointsUtil.JILIOnClickListener.RewardAdInteraction_onVideoError,AdvertisingBackdropsPointsUtil.JILIOnClickListenerSTR.RewardAdInteraction_onVideoError);

            }

            @Override
            public void onRewardVerify(boolean b, int i, String s, int i1, String s1) {
//                Logger.d("=====广告展示监听器====onRewardVerify");
                Logger.d("=====RewardAdInteractionListener====onRewardVerify===="+b+""+i+""+s+""+i1+""+s1);
                //  10111 防止黑产
//                AdvertisingBackdropsPointsUtil.getInstance().JiLiVideo(activity,"",AdvertisingBackdropsPointsUtil.JILIOnClickListener.RewardAdInteraction_onRewardVerify,"");

            }


            @Override
            public void onRewardArrived(boolean isRewardValid, int rewardType, Bundle extraInfo) {
//播放完成

//                Toaster.show(
//                        "reward_extra_key_error_code: "+extraInfo.getString("reward_extra_key_error_code")
//                       + "    \n   reward_extra_key_error_msg: "+extraInfo.getString("reward_extra_key_error_msg")
//                        +     "  \n   transId:"+extraInfo.getString("transId")
//                        +     "  \n   errorCode:"+extraInfo.getString("errorCode")
//                       +     "  \n   isRewardValid:"+isRewardValid
//                );
//
//
//                Logger.d(TAG+" reward onRewardArrived: %b,   %d",isRewardValid,rewardType);
                Logger.d("=====RewardAdInteractionListener====onRewardArrived:====");
                AdvertisingBackdropsPointsUtil.getInstance().JiLiVideo(activity,mMediaId,"",AdvertisingBackdropsPointsUtil.JILIOnClickListener.RewardAdInteraction_onRewardArrived,AdvertisingBackdropsPointsUtil.JILIOnClickListenerSTR.RewardAdInteraction_onRewardArrived);

//                Logger.d("=====广告展示监听器====reward onRewardArrived:===="+isRewardValid+"   "+rewardType);
//                Logger.d("=====广告展示监听器====reward onRewardArrived:===="+extraInfoM);
                isRewardValidM = isRewardValid;
                extraInfoM = extraInfo;
            }

            @Override
            public void onSkippedVideo() {
                Logger.d("=====RewardAdInteractionListener====onSkippedVideo:====");
                AdvertisingBackdropsPointsUtil.getInstance().JiLiVideo(activity,mMediaId,"",AdvertisingBackdropsPointsUtil.JILIOnClickListener.RewardAdInteraction_onSkippedVideo,AdvertisingBackdropsPointsUtil.JILIOnClickListenerSTR.RewardAdInteraction_onSkippedVideo);
                callbackFail();
            }
        };
    }


}
